package com.hdax.controller;

import com.hdax.entity.Permission;
import com.hdax.entity.Role;
import com.hdax.entity.User;
import com.hdax.service.PermissionService;
import com.hdax.service.RoleService;
import com.hdax.validateCode.ValidateCode;
import com.hdax.vo.ActiveUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;

@RestController
public class LoginController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    @GetMapping("/login")
    public ModelAndView login(){
        return new ModelAndView("login");
    }

    // 验证登录
    @PostMapping("/login")
    public String login(ActiveUser activeUser, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String validateCode = (String) session.getAttribute("validateCode");
        String randomCode = request.getParameter("randomCode");
        if (randomCode != null && validateCode != null && !randomCode.equals(validateCode)) {
            return "验证码错误";
        }
        Subject subject = SecurityUtils.getSubject();
        String msg="success";
        if (!subject.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken(activeUser.getUsername(), activeUser.getPassword());
            //是否记住我
            token.setRememberMe(activeUser.getRememberMe());
            try {
                subject.login(token);
                session.setAttribute("activeUser",activeUser);
            } catch (UnknownAccountException e) {
                e.printStackTrace();
                msg= "用户名不存在";
            } catch (IncorrectCredentialsException e) {
                e.printStackTrace();
                msg= "密码错误";
            }catch (DisabledAccountException e){
                msg= "该用户不存在";
            } catch (AuthenticationException e) {
                e.printStackTrace();
            }
        }
        return msg;
    }


    //    生成验证码
    @RequestMapping("/validateCode")
    public void validateCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Cache-Control", "no-cache");
        String verifyCode = ValidateCode.generateTextCode(ValidateCode.TYPE_NUM_LOWER, 4, null);
        request.getSession().setAttribute("validateCode", verifyCode);
        System.out.println(verifyCode);
        response.setContentType("image/jpeg");
        BufferedImage bim = ValidateCode.generateImageCode(verifyCode, 90, 30, 5, true, Color.WHITE, Color.BLUE, null);
        ImageIO.write(bim, "JPEG", response.getOutputStream());
    }
    // 登出
    @RequestMapping("/logout")
    public ModelAndView exit(){
        return new ModelAndView("login");
    }

    //     跳到主页面
    @GetMapping("/index")
    public ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView("index");
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        System.out.println(user);
        Integer roleId = roleService.findRoleIdByUserName(user.getUsername());
        List<Permission> permissionList = permissionService.findParentByRoleId(roleId);
        for (Permission permission : permissionList) {
            permission.setChildren(permissionService.findChildrenByRoleId(permission.getId(),roleId));
            System.out.println(permission);
        }
        modelAndView.addObject("permissions",permissionList);

        return modelAndView;
    }

    @GetMapping("/main")
    public ModelAndView open(){
        return new ModelAndView("console");
    }

}
